# app/user/models/role.py
from datetime import datetime, timezone

from sqlmodel import Field, Relationship, SQLModel

from app.auth.models.permissions import GenericPermissions, PermissionRole


class RoleBase(SQLModel):
    name: str = Field(
        default="", max_length=50, unique=True, index=True, nullable=False
    )


class RoleCreate(RoleBase): ...


class RolePublic(RoleBase):
    created_at: datetime


class Role(RoleBase, table=True):
    id: int = Field(default=None, primary_key=True, index=True)
    is_active: bool = Field(default=True, nullable=False)
    is_deleted: bool = Field(default=False, nullable=False)
    created_at: datetime = Field(
        default_factory=lambda: datetime.now(timezone.utc), nullable=False
    )
    updated_at: datetime = Field(
        default_factory=lambda: datetime.now(timezone.utc),
        nullable=False,
        sa_column_kwargs={"onupdate": lambda: datetime.now(timezone.utc)},
    )

    # 直接关联的权限（修复后的代码）
    permissions: list[GenericPermissions] = Relationship(
        link_model=PermissionRole,
        sa_relationship_kwargs={
            "lazy": "selectin",
            "backref": "assigned_roles",
            "cascade": "save-update, merge",
        },
    )

    # 业务方法
    def assign_to_user(self, user):
        """分配给用户"""
        if user not in self.users:
            self.users.append(user)

    def revoke_from_user(self, user):
        """从用户撤销"""
        if user in self.users:
            self.users.remove(user)

    def to_dict(self):
        return {"id": self.id, "name": self.name, "is_active": self.is_active}
